package errors

import (
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

const defaultGRPCCode = codes.Internal

var grpcCodes = map[error]codes.Code{
	ErrInvalidArgs:          codes.InvalidArgument,
	ErrConflict:             codes.AlreadyExists,
	ErrInsufficientFunds:    codes.Unavailable,
	ErrInternalError:        codes.Internal,
	ErrMethodNotImplemented: codes.Unimplemented,
	ErrNoAccess:             codes.Unavailable,
	ErrNotFound:             codes.NotFound,
}

var grpcReverseCodes = map[codes.Code]error{
	codes.InvalidArgument: ErrInvalidArgs,
	codes.AlreadyExists:   ErrConflict,
	codes.Internal:        ErrInternalError,
	codes.Unimplemented:   ErrMethodNotImplemented,
	codes.Unavailable:     ErrNoAccess,
	codes.NotFound:        ErrNotFound,
}

func GRPC(err Error) error {
	currentStatus, ok := grpcCodes[err]

	if !ok {
		return status.Error(defaultGRPCCode, err.Error())
	}

	return status.Error(currentStatus, err.Error())
}

func ErrorTypeGRPC(grpcErr error) error {
	status, ok := status.FromError(grpcErr)
	if !ok {
		return ErrInternalError
	}

	err, ok := grpcReverseCodes[status.Code()]
	if !ok {
		return ErrInternalError
	}

	return err
}
